let mta = require('../../utils/mta_analysis.js');
Page({
    data: {
        msg: '请扫码开门或定位门店',
        isLoading: true,
        urlAddress: getApp().globalData.imageUrl,
        isFirst: true,
        isShow: false,
        openid: '',
        userInfo: {},
        isHaveShopCode: false,
        isMustPosition: false,
        isLogin: false

    },
    onLoad: function (options) {
        // console.log(1)
        if (options.memId) {
            getApp().globalData.common.recommendId = options.memId;
        }
        if (options.groupCode) {
            getApp().globalData.common.groupCode = options.groupCode;
        }
        //埋点
        mta.Page.init();
        mta.Event.stat("smg_shouye", {});
        mta.Event.stat("smg_loding", {})
        // this.getWiFi();
        //判断是否扫码
        if (options.shopCode) {
            getApp().globalData.common.shopCode = options.shopCode;
            getApp().globalData.common.reserveShopCode = options.shopCode;
            getApp().globalData.common.souce = options.souce;
            getApp().globalData.common.ST = options.ST;

            wx.setStorageSync('shopCode', options.shopCode);
            this.setData({
                isHaveShopCode: true
            })
        }
        console.log("****load")
        console.log(wx.getStorageSync('shopCode'))
        //判断是否有店铺code缓存
        if (wx.getStorageSync('shopCode')) {
            this.setData({
                isMustPosition: true
            })
        }



    },
    loginNo:function(){
       wx.navigateTo({
            url: '../reserveShops/reserveShops'
          })


    },
    onReady: function () {

    },
    onShow: function (options) {
       
        //判断是否有用户缓存
        if (wx.getStorageSync('openId')) {
            if (wx.getStorageSync('falg')) {
                //     //this.getUserId();
                    this.setData({
                        isFirst: true,
                        isLogin:true
                    });
                // } else {
                //     this.setData({
                //         isFirst: false
                //     });
                //this.appletLogin();
                this.getUserId();
            }else{
              this.appletLogin();  
            }
        } else {
            this.getUserId();
        }
    },
    onHide: function () {
        // 页面隐藏
    },

    onUnload: function () {
        // 页面关闭
    },
    loginMen() {
        this.setData({
            isLogin: true
        })
    },

    //
    getUserId: function () {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        var _self = this;
        wx.login({
            success: function (res) {
                wx.hideLoading();
                if (res.code) {
                    var code = res.code;
                    console.log(code);
                    // return;
                    _self.acquireOpenId(code)
                } else {

                }
            },
            fail: function (res) {
                console.log(res)
            }
        });

    },
    //用code获取openId,是否是新用户,并缓存 
    acquireOpenId: function (code) {
        var _self = this;
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        wx.request({
            url: getApp().globalData.baseUrl + '/applet/autoLogin.do',
            data: {
                code: code
            },
            success: function (response) {
                wx.hideLoading();
                const res = response.data
                if (res.code == 200) {
                    if (res.obj.first) {
                        _self.setData({
                            isFirst: true,
                            openid: res.obj.openId
                        });
                        wx.setStorageSync('openId', res.obj.openId);
                        wx.setStorageSync('memberId', res.obj.memId);
                        wx.setStorageSync('falg', true);
                        _self.getUserInfo();
                    } else {
                        //老用户   
                        _self.setData({
                            isFirst: false,
                            openid: res.obj.openId
                        });
                        wx.setStorageSync('falg', false);
                        getApp().globalData.userInfo = res.obj;
                        wx.setStorageSync('memberId', res.obj.memId);
                        wx.setStorageSync('openId', res.obj.openId);
                        _self.appletLogin();
                    }
                    return
                } else {
                    _self.setData({
                        isFirst: false
                    });
                    _self.showMyToast(_self, res.des)
                }
            }
        })
    },
    //老用户根据openid登录
    appletLogin: function () {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        var _self = this
        wx.request({
            url: getApp().globalData.baseUrl + '/applet/login.do',
            method: 'get',
            data: {
                openId: wx.getStorageSync('openId'),
            },
            success: function (res) {
                wx.hideLoading();
                if (res.data.code == 200) {
                    getApp().globalData.userInfo = res.data.obj;
                    // getApp().globalData.userInfo.memId = res.data.obj.memId;
                    // getApp().globalData.userInfo.nickName = res.data.obj.nickName;
                    // getApp().globalData.userInfo.avatarUrl = res.data.obj.avatarUrl;
                    // getApp().globalData.userInfo.gender = res.data.obj.gender;
                    // getApp().globalData.userInfo.level = res.data.obj.level;
                    // getApp().globalData.userInfo.isBind = res.data.obj.isBind;
                    getApp().globalData.header.Cookie = 'SESSION=' + res.data.obj.session;
                    // console.log('getApp().globalData.common.groupCode')
                    // console.log(getApp().globalData.common.groupCode)
                    if (getApp().globalData.common.deviceCode || getApp().globalData.common.TS == 4) {
                        const version = wx.getSystemInfoSync().SDKVersion;
                        if (_self.compareVersion(version, '2.1.0') != -1) {
                            wx.navigateTo({
                                url: '../newScan/newScan'
                            })
                        } else {
                            wx.navigateTo({
                                url: '../scan/scan'
                            })
                        }
                        return
                    }
                    if (getApp().globalData.common.groupCode) {
                        wx.redirectTo({
                            url: '../myGroupDetail/myGroupDetail?groupCode=' + getApp().globalData.common.groupCode
                        })
                        return
                    }
                    if (_self.data.isHaveShopCode) {

                        if (getApp().globalData.common.souce == 3) {
                            wx.redirectTo({
                                url: '../reserveShops/reserveShops'
                            })
                        }
                        if (getApp().globalData.common.ST == 2) {
                            wx.redirectTo({
                                url: '../reserveShops/reserveShops'
                            })
                        } else if (getApp().globalData.common.ST == 1) {
                            wx.redirectTo({
                                url: '../newReserve/newReserve'
                            })
                        } else {
                            wx.redirectTo({
                                //url: '../newIndex/newIndex'
                                url: '../reserveShops/reserveShops'
                            })
                        }


                    } else {
                        wx.redirectTo({
                            //url: '../newIndex/newIndex'
                            url: '../reserveShops/reserveShops'
                        })
                        mta.Event.stat("smg_loding_position", {})
                        _self.getfaceCode();

                    }
                } else {
                    _self.loadingErr();
                    _self.setData({
                        isFirst: false
                    });
                    //console.log(110011+"_____________________");
                    _self.showMyToast(_self, res.data.des, 5000)
                }
            }
        })
    },
    //获取人脸识别头像
    getfaceCode: function () {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        var _self = this;
        wx.request({
            url: getApp().globalData.baseUrl + '/applet/shop/getFaceLocation.do',
            method: 'get',
            header: getApp().globalData.header,
            data: {
                openId: wx.getStorageSync('openId'),
            },
            success: function (res) {

                console.log("人脸识别结果")
                console.log(res)
                //console.log(res)
                wx.hideLoading();
                if (res.data.code == 200) {
                    //_self.showMyToast(_self, res.data.obj.shopCode, 10000)
                    mta.Event.stat("smg_renlainshibie", {});
                    wx.setStorageSync('shopCode', res.data.obj.shopCode);
                    getApp().globalData.common.shopCode = res.data.obj.shopCode;
                    wx.redirectTo({
                        // url: '../newIndex/newIndex'
                        url: '../index/index'
                    })
                } else {
                    if (_self.data.isMustPosition) {
                        // _self.showMyToast(_self, res.data.des, 10000)
                        _self.getShopCode();
                    }

                }
            }
        })

    },
    getShopCode: function () {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        var _self = this;
        wx.getLocation({
            type: 'gcj02',
            success: function (res) {

                var latitude = res.latitude
                var longitude = res.longitude
                var speed = res.speed
                var accuracy = res.accuracy
                getApp().globalData.common.longitude = longitude;
                getApp().globalData.common.latitude = latitude;
                console.log("longitude" + longitude)
                console.log("latitude" + latitude)
                wx.request({
                    url: getApp().globalData.baseUrl + '/applet/shop/relateShop.do',
                    data: {
                        longitude: longitude,
                        latitudes: latitude,
                        shopCode: wx.getStorageSync('shopCode')
                    },
                    header: {
                        'content-type': 'application/json' // 默认值
                    },
                    success: function (res) {

                        wx.hideLoading();
                        var shopCode = wx.getStorageSync('shopCode')
                        if (res.data.code == 200) {

                            if (res.data.obj.shopCode != shopCode) {
                                wx.redirectTo({
                                    //url: '../newIndex/newIndex'
                                    url: '../reserveShops/reserveShops'
                                })
                            } else {
                                _self.setData({
                                    isHaveShopCode: true
                                });
                                getApp().globalData.common.shopCode = res.data.obj.shopCode;
                                getApp().globalData.common.shopName = res.data.obj.shopName;
                                wx.redirectTo({
                                    // url: '../newIndex/newIndex'
                                    url: '../reserveShops/reserveShops'
                                })

                            }

                        } else {
                            wx.redirectTo({
                                //url: '../newIndex/newIndex'
                                url: '../reserveShops/reserveShops'
                            })
                        }

                    }
                })
            },
            fail: function () {
                wx.hideLoading();
                console.log("失败")
            }
        })

    },

    //获取用户信息
    getUserInfo: function () {
        // wx.showLoading({
        //     title: '加载中',
        //     mask: true
        // });
        // var _self = this;
        // wx.getUserInfo({
        //     success: function(res) {
        //         wx.hideLoading();
        //         var userInfo = res.userInfo
        //         console.log(res.userInfo)
        //         _self.setData({
        //             userInfo: userInfo
        //         });
        //         getApp().globalData.userInfo.nickName = userInfo.nickName;
        //         getApp().globalData.userInfo.avatarUrl = userInfo.avatarUrl;
        //         getApp().globalData.userInfo.gender = userInfo.gender;
        //         // wx.showToast({
        //         //     title: "获取用户昵称:" + userInfo.nickName,
        //         //     image: '../../image/error.png',
        //         //     duration: 2000
        //         // })
        //     },
        //     fail: function() {
        //         wx.hideLoading();
        //     }
        // }) 

        this.setData({
            userInfo: null
        })
        getApp().globalData.userInfo.nickName = "";
        getApp().globalData.userInfo.avatarUrl = "";
        getApp().globalData.userInfo.gender = "";
        // this.appletLogin();
         wx.redirectTo({
                url: '../reserveShops/reserveShops'
             })
        // this.loginMen();

    },
    //获取用户手机号
    getPhoneNumber: function (e) {
        console.log("获取用户手机号");
        mta.Event.stat("smg_zhuce", {});
        if (!e.detail.iv || !e.detail.encryptedData) {
            mta.Event.stat("smg_btbushouquanshouji", {});
            this.loadingErr();
        } else {
            mta.Event.stat("smg_btshouquanshouji", {});
            this.decryption(wx.getStorageSync('openId'), e.detail.iv, e.detail.encryptedData);
        }

    },
    //手机号解密、注册
    decryption: function (id, iv, encryptedData) {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        var _self = this;
        console.log(_self.data.userInfo);
        wx.request({
            url: getApp().globalData.baseUrl + '/applet/decryptMobile.do',
            method: 'post',
            // header: getApp().globalData.header,
            data: {
                openId: id,
                iv: iv,
                encryptedData: encryptedData,
                platform: 6,
                shopCode: getApp().globalData.common.shopCode,
                userInfo: _self.data.userInfo,
                recommendId: getApp().globalData.common.recommendId
            },
            success: function (res) {
                wx.hideLoading();
                if (res.data.code == 200) {
                    _self.setData({
                        isFirst: false
                    });
                    wx.setStorageSync('falg', false);
                    getApp().globalData.userInfo = res.data.obj;
                    //getApp().globalData.userInfo.memId = res.data.obj.memId;
                    // getApp().globalData.userInfo.nickName = res.data.obj.nickName;
                    // getApp().globalData.userInfo.avatarUrl = res.data.obj.avatarUrl;
                    // getApp().globalData.userInfo.gender = res.data.obj.gender;
                    // getApp().globalData.userInfo.level = res.data.obj.level;
                    // getApp().globalData.userInfo.isBind = res.data.obj.isBind;
                    getApp().globalData.header.Cookie = 'SESSION=' + res.data.obj.session;
                    if (getApp().globalData.common.deviceCode || getApp().globalData.common.TS == 4) {
                        const version = wx.getSystemInfoSync().SDKVersion;
                        if (_self.compareVersion(version, '2.1.0') != -1) {
                            wx.navigateTo({
                                url: '../newScan/newScan'
                            })
                        } else {
                            wx.navigateTo({
                                url: '../scan/scan'
                            })
                        }
                        return
                    }
                    if (getApp().globalData.common.groupCode) {
                        wx.redirectTo({
                            url: '../myGroupDetail/myGroupDetail?groupCode=' + getApp().globalData.common.groupCode
                        })
                        return
                    }
                    if (_self.data.isHaveShopCode) {
                        if (getApp().globalData.common.souce == 3) {
                            wx.redirectTo({
                                url: '../reserveShops/reserveShops'
                            })
                        }
                        if (getApp().globalData.common.ST == 2) {
                            wx.redirectTo({
                                url: '../reserveShops/reserveShops'
                            })
                        }
                        if (getApp().globalData.common.ST == 1) {
                            wx.redirectTo({
                                url: '../newReserve/newReserve'
                            })
                        } else {
                            wx.redirectTo({
                                // url: '../newIndex/newIndex'
                                url: '../reserveShops/reserveShops'
                            })
                        }

                    } else {
                        wx.redirectTo({
                            //url: '../newIndex/newIndex'
                            url: '../reserveShops/reserveShops'
                        })
                    }
                } else if (res.data.code == 999) {
                    _self.showMyToast(_self, res.data.des, 5000)
                } else {
                    _self.loadingErr();
                }

            }
        })

    },
    showMyToast: function (self, my_toast_tip, time = 2000, template = 'my_toast') {
        self.setData({
            template: template, //my_toast
            my_toast_tip: my_toast_tip
        })
        setTimeout(() => {
            self.setData({
                template: '', //my_toast
                my_toast_tip: ''
            })
        }, time)
    },
    turnAction: function () {
        mta.Event.stat("smg_btjiazaitiaoguo", {});
        getApp().globalData.common.shopCode = null;
        wx.redirectTo({
            // url: '../newIndex/newIndex'
            url: '../reserveShops/reserveShops'
        })
    },
    scanAction: function () {
        var _self = this;
        wx.scanCode({
            success: (res) => {
                console.log(res);
                if (res.result.split("?")[1]) {
                    var shopCode = "";
                    var type = "";
                    var shopType = '';
                    shopCode = res.result.split("?")[1];
                    console.log(shopCode + "====")
                    if (!shopCode) {
                        wx.showToast({
                            title: '此码非小程序码',
                            image: '../../image/error.png',
                            duration: 1000
                        })
                    } else {
                        shopType = shopCode.split("&")[2];
                        if (shopType) {
                            shopType = shopType.split("=")[1];
                        }

                        type = shopCode.split("&")[1];
                        shopCode = shopCode.split("&")[0];
                        shopCode = shopCode.split("=")[1];
                        type = type.split("=")[1];
                        getApp().globalData.common.shopCode = shopCode;
                        getApp().globalData.common.souce = type;
                        getApp().globalData.common.ST = shopType;
                        wx.setStorageSync('shopCode', shopCode);

                        if (shopType == 2 || type == 3) {
                            wx.redirectTo({
                                url: '../reserveShops/reserveShops'
                            })
                        } else if (shopType == 1) {
                            wx.redirectTo({
                                url: '../newReserve/newReserve'
                            })
                        } else {
                            wx.redirectTo({
                                //url: '../newIndex/newIndex'
                                url: '../reserveShops/reserveShops'
                            })
                        }

                    }


                } else {
                    var shopCode = "";
                    var type = "";
                    var shopType = '';
                    if (!res.path) {
                        wx.showToast({
                            title: '此码非小程序码',
                            image: '../../image/error.png',
                            duration: 1000
                        })
                        return;
                    }
                    shopCode = res.path.split("?")[1];
                    type = shopCode.split("&")[1];
                    shopType = shopCode.split("&")[2];
                    if (shopType) {
                        shopType = shopType.split("=")[1];
                    }

                    shopCode = shopCode.split("&")[0];
                    shopCode = shopCode.split("=")[1];
                    type = type.split("=")[1];
                    getApp().globalData.common.shopCode = shopCode;
                    getApp().globalData.common.souce = type;
                    getApp().globalData.common.ST = shopType;
                    wx.setStorageSync('shopCode', shopCode);

                    if (shopType == 2 || type == 3) {
                        wx.redirectTo({
                            url: '../reserveShops/reserveShops'
                        })
                    } else if (shopType == 1) {
                        wx.redirectTo({
                            url: '../newReserve/newReserve'
                        })
                    } else {
                        wx.redirectTo({
                            //url: '../newIndex/newIndex'
                            url: '../reserveShops/reserveShops'
                        })
                    }
                }
            }
        })
    },
    loadingErr: function () {
        wx.navigateTo({
            url: '../login/login'
        })
    },
    compareVersion: function (v1, v2) {
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)

        while (v1.length < len) {
            v1.push('0')
        }
        while (v2.length < len) {
            v2.push('0')
        }

        for (let i = 0; i < len; i++) {
            const num1 = parseInt(v1[i])
            const num2 = parseInt(v2[i])

            if (num1 > num2) {
                return 1
            } else if (num1 < num2) {
                return -1
            }
        }

        return 0
    }
    // getWiFi: function() {
    //     wx.startWifi({
    //         success: function(res) {
    //         },
    //         faile: function(err) {
    //         }
    //     })
    //     wx.getWifiList({
    //         success: function(res) {
    //             console.log("*****")
    //             console.log(res)
    //         }
    //     })
    //     wx.onGetWifiList(function(res) {
    //         console.log("====")
    //         console.log(res)
    //     })
    //     wx.connectWifi({
    //         SSID: 'youplus',
    //         BSSID: '1c:de:a7:4e:1f:df',
    //         password: "suzhouqiao001",
    //         success: function(res) {
    //             console.log("++++")
    //             console.log(res)
    //         }
    //     })
    // }
})